package edu.gj.demo;

import com.google.gson.Gson;
import org.json.JSONObject;

import java.io.*;
import java.net.Socket;
import java.net.SocketException;

/**
 * @author Simple
 * @date 2020/4/17 15:00
 */
public class ServerThread extends Thread {


    private String clientName;

    private Socket socket;


    InputStream inputStream = null;
    InputStreamReader inputStreamReader = null;
    BufferedReader bufferedReader = null;
    OutputStream outputStream = null;
    BufferedOutputStream bufferedOutputStream = null;
    PrintStream printStream = null;


    public ServerThread(Socket socket) {
        this.socket = socket;
        try {
            socket.setKeepAlive(true);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            inputStream = socket.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            outputStream = socket.getOutputStream();
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            printStream = new PrintStream(bufferedOutputStream);
            startMessageAccept(bufferedReader);
        } catch (Exception e) {
            e.printStackTrace();
            closeResources();
        }
    }

    private void closeResources() {
        try {
            inputStream.close();
            inputStreamReader.close();
            bufferedReader.close();
            outputStream.close();
            bufferedOutputStream.close();
            printStream.close();
            socket.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 发送消息
     *
     * @param message
     */
    public void sendMessage(String message) {
        printStream.println(message);
        printStream.flush();
    }


    public void startMessageAccept(BufferedReader reader) {
        lastHeartTime = System.currentTimeMillis();
        new Thread(new NoticeTimeRunnable()).start();
        isHearting = true;
        while (isHearting) {
            try {
                String message = reader.readLine();
                MessageBean messageBean = new Gson().fromJson(message,MessageBean.class);
                JSONObject jsonObject = new JSONObject(message);
                if (messageBean.getType() == 0) {
                    //心跳消息
                    System.out.println("心跳消息" + jsonObject.toString());
                } else {
                    //正常消息
                    handleMessage(messageBean);
                }
            } catch (IOException e) {
                e.printStackTrace();
                closeResources();
                return;
            }
        }
    }


    private void handleMessage(MessageBean body) {
        System.out.println("收到消息：" + new Gson().toJson(body));
        if (body.getType() == 3){
            Server.sendMessage(body);
        }else if (body.getType() == 1){
            clientName = body.getUserName();
        }
    }


    private long lastHeartTime;
    private boolean isHearting;

    private class NoticeTimeRunnable implements Runnable{

        public void run() {
            while (true){
                try {
                    Thread.sleep(50);
                    if (System.currentTimeMillis() - lastHeartTime > 1000){
                        isHearting = false;
                        closeResources();
                        return;
                    }
                    lastHeartTime = System.currentTimeMillis();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public String getClientName() {
        return clientName;
    }



}
